<template>
    <div style="width: 100%; height: 200px; overflow-y: auto">
        <el-tree
            v-show="showMenus"
            ref="menuTree"
            :data="menus"
            show-checkbox
            node-key="id"
            :props="{
                children: 'children',
                label: 'name',
            }"
            @check="checkChanged"
        />
        <el-skeleton v-if="!showMenus" animated />
    </div>
</template>
<script lang="ts" setup>
import { getAllMenus } from '@/apis/mall/permission'

const emits = defineEmits(['update:modelValue'])
const props = defineProps({
    modelValue: {
        type: Array,
        default() {
            return []
        },
    },
})
const menuTree = ref(null)
const menus = ref([])
const showMenus = computed(() => {
    const value = menus.value
    return !!value && value.length > 0
})
const checkChanged = () => {
    const checkedMenuIds = menuTree.value.getCheckedKeys(true)
    emits('update:modelValue', checkedMenuIds)
}
watch(
    () => props.modelValue,
    (value) => {
        menuTree.value.setCheckedKeys(value)
    },
)
onMounted(() => {
    getAllMenus().then((response) => {
        menus.value = response.data
    })
    nextTick(() => {
        menuTree.value.setCheckedKeys(props.modelValue)
    })
})
</script>
<style>
.el-tree-node__content {
    height: 40px;
}
</style>
